InstanceTimer = {
  loaded = false,
  height = 32,
  fontsize1 = 20,
  fontsize2 = 14,
}

InstanceTimer.OnClick = function()
  if not InstanceTimer.loaded then return end
  if InstanceTimer.config then
    InstanceTimer.config.toggle()
  end
end

InstanceTimer.getDbVal = function(path)
  local current = InstanceTimerDB
  local keys = {}
  -- 将路径按点分割成多个键
  for key in string.gmatch(path, "[^%.]+") do
    table.insert(keys, key)
  end

  -- 逐级查找值
  for _, key in ipairs(keys) do
    if type(current) == "table" and current[key] ~= nil then
      current = current[key]
    else
      -- 如果某一级找不到对应的值，返回 nil
      return nil
    end
  end

  return current
end

InstanceTimer.setDbVal = function(path, value)
  local current = InstanceTimerDB
  local keys = {}
  -- 将路径按点分割成多个键
  for key in string.gmatch(path, "[^%.]+") do
    table.insert(keys, key)
  end

  -- 逐级查找或创建表
  for i = 1, table.getn(keys) - 1 do
    local key = keys[i]
    if type(current) ~= "table" then
      current = {}
    end
    if current[key] == nil then
      current[key] = {}
    end
    current = current[key]
  end

  -- 设置最终值
  local lastKey = keys[table.getn(keys)]
  if type(current) == "table" then
    current[lastKey] = value
  end
end

InstanceTimer.MinimapButton = CreateFrame("Button", "InstanceTimerMinimapButton", Minimap)
-- InstanceTimer.MinimapButton:ClearAllPoints();
InstanceTimer.MinimapButton:SetPoint("TOP", Minimap, "BOTTOM", -25, 10)
InstanceTimer.MinimapButton:EnableMouse(true)
InstanceTimer.MinimapButton:SetMovable(true)
InstanceTimer.MinimapButton:SetToplevel(true)
InstanceTimer.MinimapButton:SetWidth(33)
InstanceTimer.MinimapButton:SetHeight(33)
InstanceTimer.MinimapButton.iconTexture = InstanceTimer.MinimapButton:CreateTexture("InstanceTimerMinimapButtonIcon",
  "BACKGROUND")
-- InstanceTimer.MinimapButton.iconTexture:SetTexture("Interface\\Icons\\INV_Misc_Bomb_04") -- 炸弹
InstanceTimer.MinimapButton.iconTexture:SetTexture("Interface\\Icons\\INV_Misc_PocketWatch_01") -- 钟表
InstanceTimer.MinimapButton.iconTexture:SetWidth(18)
InstanceTimer.MinimapButton.iconTexture:SetHeight(18)
InstanceTimer.MinimapButton.iconTexture:SetPoint("TOPLEFT", InstanceTimer.MinimapButton, "TOPLEFT", 7, -5)

InstanceTimer.MinimapButton.borderTexture = InstanceTimer.MinimapButton:CreateTexture("InstanceTimerMinimapButtonBorder",
  "OVERLAY")
InstanceTimer.MinimapButton.borderTexture:SetTexture("Interface\\Minimap\\MiniMap-TrackingBorder")
InstanceTimer.MinimapButton.borderTexture:SetWidth(52)
InstanceTimer.MinimapButton.borderTexture:SetHeight(52)
InstanceTimer.MinimapButton.borderTexture:SetPoint("TOPLEFT", InstanceTimer.MinimapButton, "TOPLEFT")

InstanceTimer.MinimapButton.hltexture = InstanceTimer.MinimapButton:SetHighlightTexture(
  "Interface\\Minimap\\UI-Minimap-ZoomButton-Highlight", "ADD")

InstanceTimer.MinimapButton:RegisterForDrag("LeftButton")
InstanceTimer.MinimapButton:SetScript("OnClick", InstanceTimer.OnClick)
InstanceTimer.MinimapButton:SetScript("OnEnter", function()
  GameTooltip:SetOwner(this, "ANCHOR_BOTTOMLEFT");
  -- GameTooltip:SetText(InstanceTimer.L["SDPS"]);
  GameTooltip:SetText(GetAddOnMetadata("InstanceTimer", "Title"));
end)
InstanceTimer.MinimapButton:SetScript("OnLeave", function()
  GameTooltip:Hide();
end)
InstanceTimer.MinimapButton:SetScript("OnDragStart", function()
  InstanceTimer.MinimapButton:StartMoving()
  InstanceTimer.MinimapButton.isMoving = true
end)
InstanceTimer.MinimapButton:SetScript("OnDragStop", function()
  InstanceTimer.MinimapButton:StopMovingOrSizing()
  InstanceTimer.MinimapButton.isMoving = false
end)

InstanceTimer.MinimapButton:Show()

-- 创建一个名为 InstanceTimerFrame 的主框架
InstanceTimerFrame = CreateFrame("Frame", "InstanceTimerFrame", UIParent)
InstanceTimerFrame:SetClampedToScreen(true)
InstanceTimerFrame:SetMovable(true)
InstanceTimerFrame:RegisterForDrag("LeftButton")
InstanceTimerFrame:SetScript("OnDragStart", function() InstanceTimerFrame:StartMoving() end)
InstanceTimerFrame:SetScript("OnDragStop", function()
  InstanceTimerFrame:StopMovingOrSizing()
  local point, _, relativePoint, offsetX, offsetY = InstanceTimerFrame:GetPoint()
  InstanceTimerDB.posX = offsetX
  InstanceTimerDB.posY = offsetY
  InstanceTimerDB.point = point
  InstanceTimerDB.relativePoint = relativePoint
end)
InstanceTimerFrame.texture = InstanceTimerFrame:CreateTexture(nil, "BACKGROUND")
InstanceTimerFrame.texture:SetTexture(0, 0, 0, 0.5)
InstanceTimerFrame.texture:SetAllPoints(InstanceTimerFrame)
-- InstanceTimerFrame:SetWidth(50) -- 测试时用
InstanceTimerFrame:SetHeight(InstanceTimer.height)

-- 让框架显示出来
InstanceTimerFrame:Show()

InstanceTimer.frames = {}
local updateFrameWidth = function()
  if table.getn(InstanceTimer.frames) > 0 then
    local w = 0
    for _, f in ipairs(InstanceTimer.frames) do
      if f:IsVisible() and f:GetAlpha() ~= 0 then
        w = w + f:GetWidth()
      end

      if not InstanceTimerFrame:GetHeight() or f:GetHeight() > InstanceTimerFrame:GetHeight() then
        InstanceTimerFrame:SetHeight(f:GetHeight() + 2)
      end
    end
    if w > 0 then
      InstanceTimerFrame:SetWidth(w + 10)
    else
      InstanceTimerFrame:SetWidth(0.001)
    end
  else
    InstanceTimerFrame:SetWidth(0.001)
  end
end
InstanceTimerFrame.updateFrameWidth = updateFrameWidth
InstanceTimer.addFrame = function(frame)
  for _, frm in ipairs(InstanceTimer.frames) do
    if frm:GetName() == frame:GetName() then
      return
    end
  end

  frame:ClearAllPoints()
  if table.getn(InstanceTimer.frames) > 0 then
    frame:SetPoint("LEFT", InstanceTimer.frames[table.getn(InstanceTimer.frames)], "RIGHT")
  else
    frame:SetPoint("LEFT", InstanceTimerFrame, "LEFT", 5, 0)
  end
  table.insert(InstanceTimer.frames, frame)
  updateFrameWidth()
end

local updateFramesPoint = function()
  local first = true
  local last
  for _, frm in ipairs(InstanceTimer.frames) do
    if frm:IsVisible() then
      frm:ClearAllPoints()
      if first then
        frm:SetPoint("LEFT", InstanceTimerFrame, "LEFT", 5, 0)
      else
        frm:SetPoint("LEFT", last, "RIGHT")
      end

      last = frm
      first = false
    end
  end
end
InstanceTimerFrame.updateFramesPoint = updateFramesPoint
InstanceTimerFrame.updateFramesWidthAndPoint = function()
  updateFrameWidth()
  updateFramesPoint()
end

local defaults = {
  showtimer = true,
  showcounter = true,
  posX = 0,
  posY = 0,
  locked = false,
  timer = {},
  logs = {},
  through = false,
  point = "CENTER",
  relativePoint = "CENTER",
}

local onLoad = function()
  if not InstanceTimerDB then InstanceTimerDB = {} end
  for k, v in pairs(defaults) do
    if InstanceTimerDB[k] == nil then
      InstanceTimerDB[k] = v
    end
  end

  for _, frm in ipairs(InstanceTimer.frames) do
    if frm.onLoad and type(frm.onLoad) == 'function' then
      frm.onLoad()
    end
  end

  if InstanceTimerDB.showtimer == false then
    InstanceTimer.timer:Hide()
  end
  if InstanceTimerDB.showcounter == false then
    InstanceTimer.boomcounter:Hide()
  end

  InstanceTimerFrame:ClearAllPoints()
  InstanceTimerFrame:SetPoint(InstanceTimerDB.point, UIParent, InstanceTimerDB.relativePoint, InstanceTimerDB.posX,
    InstanceTimerDB.posY)
  -- InstanceTimerFrame.updateFrameWidth()
  -- InstanceTimerFrame.updateFramesPoint()

  InstanceTimer.register("OPTIONS_CHANGED", InstanceTimerFrame)
end

-- -- local optionsButton = CreateFrame("Button", nil, InstanceTimerFrame)
-- -- optionsButton:SetPoint("TOPLEFT", InstanceTimerFrame, "TOPLEFT")
-- -- optionsButton:SetWidth(10)
-- -- optionsButton:SetHeight(10)
-- -- optionsButton:SetScript("OnClick", function() if InstanceTimer.config then InstanceTimer.config.toggle() end end)



-- optionsButton:SetScript("OnClick", function() if InstanceTimer.config then InstanceTimer.config.toggle() end end)

InstanceTimerFrame:RegisterEvent("ADDON_LOADED")
InstanceTimerFrame:SetScript("OnEvent", function()
  if event == "ADDON_LOADED" and arg1 == "InstanceTimer" then
    onLoad()
    InstanceTimer.toggleLocked(InstanceTimerDB.locked)
    InstanceTimer.timer.updateVisible()
    InstanceTimer.boomcounter.updateVisible()
    if InstanceTimerDB.boomcounter.showprogressalways then
      InstanceTimer.boomcounter.showLines()
    end
    InstanceTimerFrame.updateFramesWidthAndPoint()
    InstanceTimer.loaded = true
  end
end)

InstanceTimer.toggleLocked = function(value)
  if value ~= nil then
    InstanceTimerFrame:SetMovable(not value)
    InstanceTimerFrame:EnableMouse(not value)
    InstanceTimerDB.locked = value
  else
    InstanceTimerFrame:SetMovable(InstanceTimerDB.locked)
    InstanceTimerFrame:EnableMouse(InstanceTimerDB.locked)
    InstanceTimerDB.locked = not InstanceTimerDB.locked
  end

  if InstanceTimer.loaded == true then
    if InstanceTimerDB.locked then
      print("计时器已锁定")
    else
      print("计时器已解锁")
    end
  end
end

InstanceTimer.toggleThrough = function(through)
  local value = through
  if value == nil then
    value = not InstanceTimerDB.through
    InstanceTimerDB.through = value
    -- print(value == true and "已启用点击穿透" or "已停止点击穿透")
  end

  for _, frm in ipairs(InstanceTimer.frames) do
    if type(frm.buttons) == 'table' then
      for _, b in ipairs(frm.buttons) do
        b:EnableMouse(not value)
      end
    end
  end

  -- optionsButton:EnableMouse(not value)
end

local registered = {}
InstanceTimer.register = function(ev, frame)
  if not registered[ev] then
    registered[ev] = { frame }
  else
    for k, v in ipairs(registered[ev]) do
      if v:GetName() == frame:GetName() then
        return
      end
    end

    table.insert(registered[ev], frame)
  end
end

InstanceTimer.trigger = function(ev, a1, a2, a3, a4, a5, a6, a7, a8, a9)
  local list = registered[ev]
  if list then
    for k, v in ipairs(list) do
      if type(v[ev]) == 'function' then
        v[ev](a1, a2, a3, a4, a5, a6, a7, a8, a9)
      end
    end
  end
end

InstanceTimerFrame.OPTIONS_CHANGED = function(key, value)
  if key == 'through' then
    InstanceTimer.toggleThrough(value)
  elseif key == 'locked' then
    InstanceTimer.toggleLocked(value)
  -- elseif key == 'showtimer' or key == 'showcounter' then
  --   updateFrameWidth()
  --   updateFramesPoint()
  -- elseif key == "boomcounter.showprogressalways" then
  --   if value == true then
  --     InstanceTimer.boomcounter.showLines()
  --   else
  --     InstanceTimer.boomcounter.hideLines()
  --   end
  -- elseif key == "timer.hidenotininstance" then
  --   if value == true and not InstanceTimer.boomcounter.inInstance() then
  --     InstanceTimer.timer:Hide()
  --     updateFrameWidth()
  --     updateFramesPoint()
  --   elseif InstanceTimerDB.showtimer then
  --     InstanceTimer.timer:Show()
  --     updateFrameWidth()
  --     updateFramesPoint()
  --   end
  elseif key == "boomcounter.hiddenlimit" then
  end
end

SlashCmdList["INSTANCE_TIMER"] = function(msg)
  if msg == "lock" then
    -- 锁定框架，禁止移动
    InstanceTimer.toggleLocked(true)
  elseif msg == "unlock" then
    -- 解锁框架，允许移动
    InstanceTimer.toggleLocked(false)
  elseif msg == "options" or msg == "opt" or msg == "o" then
    if InstanceTimer.config then
      InstanceTimer.config.toggle()
    end
  -- elseif string.match(msg, '^addap') then
  --   local from, to = string.find(msg, ' ')
  --   if from then
  --     local name = string.sub(msg, from)
  --     InstanceTimer.timer.addAutoPauseName(name)
  --   end
  -- elseif string.match(msg, '^rmap') then
  --   local from, to = string.find(msg, ' ')
  --   if from then
  --     local name = string.sub(msg, from)
  --     InstanceTimer.timer.removeAutoPauseName(name)
  --   end
  -- elseif msg == 'showap' then
  --   InstanceTimer.timer.showAutoPauseName()
  elseif msg == 'tgtimer' then
    -- 切换计时 / 暂停
    InstanceTimer.timer.toggle()
  -- elseif msg == 'tgshow' then
  --   -- 切换显示隐藏
  --   local visible = false
  --   for _,frm in ipairs(InstanceTimer.frames) do
  --     if frm:IsVisible() then
  --       visible = true
  --       break
  --     end
  --   end

  --   if visible == true then
  --     for _,frm in ipairs(InstanceTimer.frames) do
  --       frm:Hide()
  --     end
  --     InstanceTimerFrame.updateFrameWidth()
  --     -- InstanceTimerFrame.updateFramesPoint()
  --   else
  --     if InstanceTimerDB.showtimer == true then
  --       InstanceTimer.timer:Show()
  --     end
  --     if InstanceTimerDB.showcounter == true then
  --       InstanceTimer.boomcounter:Show()
  --     end
  --     InstanceTimerFrame.updateFrameWidth()
  --     if InstanceTimerFrame:GetWidth() > 10 then
  --       InstanceTimerFrame.updateFramesPoint()
  --     end
  --   end
  elseif msg == 'tgth' then
    -- 切换点击穿透
    InstanceTimer.toggleThrough()
    InstanceTimer.config.setVal('through', InstanceTimerDB.through)
  elseif msg == 'stop' then
    InstanceTimer.timer.stop(true)
  elseif msg == 'restart' then
    InstanceTimer.timer.start(true)
  elseif msg == 'start' then
    InstanceTimer.timer.start()
  end
end
SLASH_INSTANCE_TIMER1 = "/itimer"
